<script setup lang="ts">
import { reactive, ref } from "vue"
// import { billListCurrent2Api, inListsApi, doBatchSellApi } from "@/api/bill"
import { doBatchSellApi as doBatchSellApi, billListCurrent2Api, inListsApi } from "@/api/billv2"
import { ElMessage } from "element-plus"
import price from "./company.vue"
const priceRef = ref<any>(null)
const dialog = ref<boolean>(false)
const loading = ref<boolean>(false)
const rightValue = ref<[]>([])
const tableData = ref<[]>([])
const data = ref<[]>([])
const listData = ref<any>([])
const total = ref(0)
const billAmount = ref(0)
const steps = ref(1)
const width = ref<string>("800")
const state = ref("")
const uid = ref<undefined | number>(undefined)
const company_id = ref<number>(0)

const billListCurrent2 = () => {
  loading.value = true
  billListCurrent2Api({}).then((res: any) => {
    data.value = res.data.list
    total.value = res.data.total
    billAmount.value = res.data.billAmount
    loading.value = false
  })
}
//#region 显示
const listShow = async () => {
  dialog.value = true
  tableData.value = []
  state.value = ""
  company_id.value = 0
  uid.value = undefined
  listData.value = []
  // 请求数据
  billListCurrent2()
}
defineExpose({ listShow })
//#endregion

//#region 关闭
const closes = () => {
  rightValue.value = []
  steps.value = 1
  width.value = "800"
  dialog.value = false
  emit("transferClose", true)
}
const handleClose = (done: () => void) => {
  done()
  closes()
}
const emit = defineEmits(["transferClose"])
//#endregion

const submit = () => {
  console.log(rightValue.value)
  if (rightValue.value.length == 0) {
    ElMessage.warning("请选择要出库的票据111")
    return
  }
  inLists(rightValue.value.join(", "))
  getAdminList()
  steps.value = 2
  width.value = "80%"
}

const inLists = (ids: string) => {
  inListsApi({
    ids: ids
  }).then((res: any) => {
    tableData.value = res.data
    tableData.value.forEach((item: any) => {
      // 使用 Decimal 将 billAmount 乘以 10000 并转换为数字类型
      item.transaction_amount = new Decimal(item.billAmount).times(10000).toNumber()
    })
    console.log(res)
  })
}

//#region 添加企业
const addCompany = () => {
  if (priceRef.value) {
    priceRef.value.show()
  }
}
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: queryString
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

const handleSelect = (item: any) => {
  uid.value = item.uid
  company_id.value = item.id
}

//#endregion

//#region vxe-grid
import Decimal from "decimal.js"
import bignumber from "bignumber.js"
import { generateDiscount, generatePrice } from "@/utils/common"
import { VxeTablePropTypes } from "vxe-table"
import { getAdminRoleListApi } from "@/api/system"
import { companyListApi } from "@/api/conventional"

const sumNum = (list: any, field: string) => {
  let count = new bignumber(0)
  list.forEach((item: any) => {
    // count = count.add(new Decimal(item[field]));
    console.log(typeof item[field])
    // 创建 Decimal 对象并进行累加
    const valueToAdd = new bignumber(item[field] || 0)
    count = count.plus(valueToAdd)
  })
  return count.toNumber()
}

const footerMethod: VxeTablePropTypes.FooterMethod<any> = ({ columns, data }) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "统计"
      }
      if (["billAmount", "out_discount", "out_finally"].includes(column.field)) {
        return sumNum(data, column.field)
      }

      return null
    })
  ]
}

const handleInput = (row: any) => {
  const { finallyAmount, discountAmount } = generatePrice(
    row.out_price,
    row.out_finally,
    row.out_discount,
    row.billAmount,
    false
  )
  // row.out_price = price
  row.out_finally = finallyAmount
  row.out_discount = discountAmount
}
const handleDiscount = (row: any) => {
  const { price, finallyAmount } = generateDiscount(
    row.out_price,
    row.out_finally,
    row.out_discount,
    row.billAmount,
    false
  )
  row.out_price = price
  row.out_finally = finallyAmount
  // row.out_discount = discountAmount
}
const handleFinally = (row: any) => {
  const billAmount = new Decimal(row.billAmount).times(10000)
  const out_finally = new Decimal(row.out_finally)
  const discountAmount = billAmount.minus(out_finally).toNumber()
  const { price } = generateDiscount(row.out_price, row.out_finally, discountAmount, billAmount.toString(), true)
  row.out_price = price.toFixed(2)
  // row.out_finally = finallyAmount
  row.out_discount = discountAmount
}

const handleTransactionAmount = (row: any) => {
  // 如果每十万价格和贴息费都为0，则跳过计算
  if (row.out_price === 0 && row.out_discount === 0) {
    return
  }
  // 判断交易金额是否大于票面金额
  const billAmountInYuan = new Decimal(row.billAmount).times(10000) // 票面金额(元)
  if (new Decimal(row.transaction_amount).greaterThan(billAmountInYuan)) {
    ElMessage.error("交易金额不能大于票面金额")
    row.transaction_amount = billAmountInYuan.toNumber()
    return
  }

  const transaction_amount = new Decimal(row.transaction_amount || 0)

  // 判断是否存在每十万价格
  if (row.out_price > 0) {
    // 如果存在每十万价格，使用generatePrice函数计算
    const { finallyAmount, discountAmount } = generatePrice(row.out_price, 0, 0, transaction_amount.toString(), true)

    // 更新行数据
    row.out_finally = finallyAmount
    row.out_discount = discountAmount
  } else {
    // 如果存在贴息费，使用generateDiscount函数计算
    const { price, finallyAmount } = generateDiscount(
      row.out_price,
      0,
      row.out_discount,
      transaction_amount.toString(),
      true
    )
    // 更新行数据
    row.out_price = price.toFixed(2)
    row.out_finally = finallyAmount
  }
}

//#endregion

//#region 表单
const formData = reactive({
  bill_type: 1,
  bill_id: 0,
  recognizerDate: "",
  billNo: "",
  acceptorName: "",
  billAmount: 0,
  price: 0,
  money: 0,
  moneys: 0,
  expirationDate: "",
  billRangeUpper: "",
  billRangeLower: "",
  is_flaw: 1,
  bill_back_user: ""
})
const formLabelWidth = "80px"

//#endregion

const onClick = async () => {
  if (state.value == "") {
    ElMessage.warning("请选择出票客户")
    return false
  }

  const batch_list = tableData.value.map((item: any) => {
    return {
      inventory_id: item.inventory_id,
      out_time: item.out_time,
      out_checks: item.out_checks,
      out_invoicings: item.out_invoicings,
      out_price: item.out_price,
      out_discount: item.out_discount,
      out_finally: item.out_finally,
      transaction_amount: item.transaction_amount
    }
  })

  await doBatchSellApi({
    out_company_id: company_id.value,
    out_admin_id: uid.value,
    batch_list: batch_list
  })
  tableData.value = []
  state.value = ""
  company_id.value = 0
  uid.value = undefined
  listData.value = []
  ElMessage.success("修改成功")
  closes()
}

const sexList1 = ref([
  { label: "是", value: 1 },
  { label: "否", value: 2 }
])
const formatSex = (value: number) => {
  if (value === 1) {
    return "是"
  }
  if (value === 2) {
    return "否"
  }
  return ""
}

const setAllEnterInvoicings = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.out_invoicings = value
  })
}
const setAllEnterChecks = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.out_checks = value
  })
}

const value2 = ref("")
const shortcuts = [
  {
    text: "今天",
    value: new Date()
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    }
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    }
  }
]
const handleDateChange = (value: any) => {
  tableData.value.forEach((row: any) => {
    row.out_time = value
  })
  console.log(value)
}
const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")
</script>

<template>
  <el-dialog
    v-model="dialog"
    v-loading="loading"
    title=""
    :width="width"
    :before-close="handleClose"
    destroy-on-close
    draggable
  >
    <div v-if="steps == 1">
      <div class="transfer">
        <el-transfer
          v-model="rightValue"
          :props="{
            key: 'inventory_id',
            label: 'billNo'
          }"
          class="custom-transfer"
          filterable
          :titles="['待选', '已选']"
          :data="data"
        >
          <template #default="{ option }">
            <div>
              <span>{{ option.billNo }} - {{ option.billAmount }}</span>
            </div>
          </template>
        </el-transfer>
      </div>
      <span class="footer">
        <el-button type="primary" @click="submit"> 提 交 </el-button>
      </span>
    </div>
    <div v-if="steps == 2">
      <div class="heads">
        <el-button type="primary" text @click="addCompany()">添加企业信息</el-button>
      </div>
      <div class="demo-drawer__content">
        <el-form :model="formData" :inline="true" size="large">
          <!-- <el-form-item label="类型" :label-width="formLabelWidth">
            <el-select v-model="formData.bill_type" placeholder="请选择">
              <el-option v-for="item in bill_type_options" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="企业" :label-width="formLabelWidth" class="custom-label">
            <el-autocomplete
              v-model="state"
              :fetch-suggestions="querySearchAsync"
              value-key="company_name"
              placeholder="请输入"
              @select="handleSelect"
            />
          </el-form-item>
          <el-form-item label="业务员" :label-width="formLabelWidth">
            <el-select v-model="uid" placeholder="请选择" disabled>
              <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-divider />
        <div>
          <div class="heads2">
            <div class="bolck">
              <el-button type="primary" @click="setAllEnterInvoicings(1)">一键开票</el-button>
              <el-button type="primary" @click="setAllEnterInvoicings(2)">取消开票</el-button>
            </div>
            <div class="bolck">
              <el-button type="primary" @click="setAllEnterChecks(1)">一键先款先票</el-button>
              <el-button type="primary" @click="setAllEnterChecks(2)">取消先款先票</el-button>
            </div>
            <div class="bolck">
              <el-date-picker
                v-model="value2"
                type="datetime"
                placeholder="请选择"
                :shortcuts="shortcuts"
                :format="customDateTimeFormat"
                :value-format="customDateTimeFormat"
                @change="handleDateChange"
              />
            </div>
          </div>
          <vxe-table
            border
            show-overflow
            :data="tableData"
            show-footer
            :column-config="{ resizable: true }"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
            :footer-method="footerMethod"
          >
            <vxe-column type="seq" width="60" />
            <vxe-column field="acceptorName" title="承兑人" />
            <vxe-column field="expirationDate" title="到期日" width="180" />
            <vxe-column field="billNo" title="票号" width="180" />
            <vxe-column field="billAmount" title="票面金额" width="180" />
            <vxe-column
              field="transaction_amount"
              title="交易金额(元)"
              width="180"
              :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.transaction_amount"
                  @input="handleTransactionAmount(row)"
                  type="number"
                  placeholder="请输入"
                />
              </template>
            </vxe-column>
            <vxe-column field="out_price" title="每十万价格" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.out_price" @input="handleInput(row)" type="number" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="out_discount" title="贴息费" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.out_discount" @input="handleDiscount(row)" type="number" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="out_finally" title="实付金额" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.out_finally" @input="handleFinally(row)" type="number" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="out_time" title="出库时间" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.out_time" type="datetime" placeholder="请选择入库时间" transfer />
              </template>
            </vxe-column>
            <vxe-column field="out_invoicings" title="开票" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatSex(row.out_invoicings) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.out_invoicings" transfer>
                  <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="out_checks" title="先款先票" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatSex(row.out_checks) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.out_checks" transfer>
                  <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
                </vxe-select>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <span class="footer">
        <el-button type="primary" @click="onClick">提交</el-button>
      </span>
    </div>
    <price ref="priceRef" />
  </el-dialog>
</template>

<style scoped>
.custom-transfer {
  /* 调整宽度 */
  width: 100% !important; /* 或者具体的像素值，例如 600px */
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.transfer >>> .el-transfer-panel {
  width: 280px;
}
.footer {
  display: flex;
  margin-top: 10px;
  justify-content: flex-end;
}
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.demo-drawer__footer {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}
.heads2 {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}
.heads2 .bolck {
  margin-left: 10px;
}
</style>
